package cn.tannn.captcha.api;

import cn.tannn.captcha.sdk.module.CaptchaVO;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.concurrent.TimeUnit;

/**
 * guava的缓存
 *
 * @author tn
 * @date 2021-09-13 16:07
 */
public class GuavaCache {
    private static Cache<String, CaptchaVO> imageCaptchaCache;


    /**
     * 图形验证 cache
     * 本地内存存储，后期让这个跟redis并存，加个特性开关
     *
     * @param expireTime 过期时间/秒
     * @return {ip:CaptchaVO}
     * @see <a href="https://wizardforcel.gitbooks.io/guava-tutorial/content/13.html">CacheBuilder</a>
     */
    public static Cache<String, CaptchaVO> imageCaptchaCache(long expireTime) {
        if (imageCaptchaCache == null) {
            imageCaptchaCache = CacheBuilder.newBuilder()
                    // 设置并发级别为cpu核心数，默认为4
                    .concurrencyLevel(Runtime.getRuntime().availableProcessors())
                    // 设置缓存在写入1分钟后失效 默认不失效 (秒)
                    .expireAfterWrite(expireTime, TimeUnit.SECONDS)
                    // 设置初始容量为500
                    .initialCapacity(5000)
                    //设置缓存最大容量为100，超过100之后就会按照LRU最近虽少使用算法来移除缓存项
                    .maximumSize(100000)
                    .build();
        }
        return imageCaptchaCache;
    }

}
